<template>
  <view class="user-info-page">
    <view class="avatar-wrap">
      <van-cell
          title="头像"
          is-link
          custom-class="cus-avatar"
      >
        <view class="user-image" >
          <image :src="userInfo.avatar"></image>
        </view>
        <view class="select-avatar-wrap">
          <button open-type="chooseAvatar" @chooseavatar="handleGetAvatar"></button>
        </view>
      </van-cell>
    </view>



    <uni-list-item
      showArrow
      clickable
      title="昵称"
      :rightText="userInfo.nickname || ''"
      :class="{ 'selected-text': userInfo.nickname }"
      @click="handleUpdateName"
    />

    <uni-list-item
      showArrow
      clickable
      title="手机号"
      :rightText="userInfo.mobile || ''"
      :class="{ 'selected-text': userInfo.mobile }"
      @click="handleUpdatePhone"
    />

    <view class="real-name">

      <uni-list-item
        showArrow
        clickable
        title="实名认证"
        @click="handleToNickName"
      >
        <template v-slot:footer>
          <view class="real-name-tag">

            <uni-tag
              v-if="userInfo.auth_type === 1"
              text="已认证"
              type="success"
            ></uni-tag>

            <uni-tag
              v-else
              text="未认证"
              type="error"
            ></uni-tag>

          </view>
        </template>
      </uni-list-item>

    </view>

    <van-action-sheet
        :show="actionSheet"
        :actions="actions"
        cancel-text="取消"
        @close="onCloseSheet"
        @cancel="cancelSheet"
        @select="onSelectSheet"
    />

    <van-dialog
        use-slot
        title="修改昵称"
        transition="fade"
        :show="showUpdateName"
        show-cancel-button
        :before-close="onBeforeCloseUpdateName"
        @close="handleSetShowUpdateName"
    >
      <view class="update-name-wrap">
        <input
          class="nick-name-input"
          type="nickname"
          v-model="nickName"
          placeholder="请输入昵称"
          :bindfocus="handleFocus"
          @change="handleChangeNickName"
          @input="handleInputNickName"
        >
      </view>
    </van-dialog>

    <van-toast id="van-toast"/>

  </view>
</template>

<script>
import Toast from 'wxcomponents/vant/toast/toast';

const app = getApp()
let cache = ''

export default {
  data() {
    return {
      showUpdateName: false,
      actionSheet: false,
      actions: [
        { name: '获取用户信息', color: '#07c160', openType: 'chooseAvatar' },
        {
          name: '拍照',
          index: 0
        },
        {
          name: '从手机相册选取',
          index: 1
        },
      ],
      nickName: '',
      userInfo: {
        id: '',
        avatar: '',
        nickname: '',
        mobile: '',
        auth_type: '',
        express_type: '',
      }
    };
  },
  methods: {
    handleUpdateAvatar() {
      this.actionSheet = true
    },
    onCloseSheet() {
      this.actionSheet = false
    },
    cancelSheet() {
      this.actionSheet = false
    },
    onSelectSheet(res) {
      const {detail} = res
      const {index} = detail

      console.log(res);

      if (index === 0) {
        this.chooseImage('camera')
      } else if (index === 1) {
        this.chooseImage('album')
      }
    },
    chooseImage(type) {
      const that = this

      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: [type],
        success: (res) => {
          const { tempFilePaths } = res
          const url = tempFilePaths[0]

          console.log(url);
        }
      })
    },
    handleUpdateName() {
      this.nickName = app.globalData.userInfo.nickname
      this.showUpdateName = true
      cache = app.globalData.userInfo.nickname
    },
    handleFocus(res) {
      console.log(res);
    },
    handleToNickName() {
      uni.navigateTo({
        url: '/pages/myFeature/realNameAuth/index'
      })
    },
    handleGetAvatar(e) {
      console.log(e);
      const {
        detail
      } = e
      const {
        avatarUrl
      } = detail

      app.upload(avatarUrl, {}, '/api/common/upload').then((res) => {
        console.log(res)
        const {
          code,
          data,
          msg
        } = res

        if (code === 1) {
          const {
            url
          } = data

          app.request({
            avatar: url
          } , '/api/logistics/user/user_edit').then((res) => {
            const {
              code,
              data,
              msg
            } = res

            if (code === 1) {
              this.userInfo.avatar = app.globalData.ftp +  url

              Toast('修改成功')
            } else {
              Toast(msg)
            }
          })
        } else {
          Toast(msg)
        }
      })
      // avatarUrl
    },

    handleInputNickName(res) {
      console.log(res);
      const {
        detail
      } = res
      const {
        value
      } = detail

      this.$nextTick(()=>{
        this.nickName = value
      })
    },

    handleChangeNickName(e) {
      const {
        value
      } = e.detail

      this.nickName = value
      cache = value
    },
    handleUpdatePhone() {
      const that = this

      uni.navigateTo({
        url: '/pages/myFeature/getUserPhone/index',
        events: {
          editSuccess: function (phoneNumber) {
            that.userInfo = {
              ...that.userInfo,
              mobile: phoneNumber
            }
          }
        }
      })
    },
    onBeforeCloseUpdateName(action) {

      return new Promise((res, rej) => {
        if (action === "confirm") {
          if (!cache) {
            Toast({
              type: 'text',
              message: '请输入昵称',
              zIndex: 99999999
            })
            res(false)
          } else {
            app.request({
              nickname: cache
            } , '/api/logistics/user/user_edit').then((res) => {
              const {
                code,
                data,
                msg
              } = res

              console.log(code);

              if (code === 1) {
                Toast({
                  type: 'text',
                  message: '修改成功',
                  zIndex: 99999999
                })
                app.globalData.event.publish('updateUserName', cache)
                app.globalData.event.publish('closeNickDialog')
              } else {
                Toast(msg)
              }
            }).finally(() => {
              res(true)
            })
          }
        } else {
          app.globalData.event.publish('closeNickDialog')
          // 点击了取消按钮
          return res(true)
        }
      })


    },
    handleSetShowUpdateName() {
      this.showUpdateName = false
    }
  },
  onLoad() {
    this.userInfo = {
      ...app.globalData.userInfo
    }

    app.globalData.event.subscribe('updateUserName', (res) => {
      app.globalData.userInfo.nickname = res
      this.userInfo = {
        ...this.userInfo,
        nickname: res
      }
    })
    app.globalData.event.subscribe('closeNickDialog',() => {
      this.showUpdateName = false
    })
  },
}
</script>

<style lang="scss">
.user-info-page {
  min-height: 100vh;
  background-color: #F2F2F2;
  .avatar-wrap {
    position: relative;
    .select-avatar-wrap {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      button {
        width: 100%;
        height: 100%;
      }
    }

  }
  .cus-avatar {
    display: flex;
    align-items: center;
  }
  .user-image {
    image {
      width: 72rpx;
      height: 72rpx;
      border-radius: 50%;
    }
  }

  .real-name {
    margin-top: 18rpx;
  }

  .update-name-wrap {
    .nick-name-input {
      width: 100%;
      padding: 0 32rpx;
      box-sizing: border-box;
      height: 52rpx;
      display: flex;
      font-size: 30rpx;
      line-height: 52rpx;
    }
  }
}
</style>

